const userService = require('../services/userService');

// 获取用户列表
const getUsers = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    
    const users = await userService.getUsers(page, limit);
    const total = await User.countDocuments();
    
    res.json({
      success: true,
      data: users,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户列表失败'
    });
  }
};

// 获取用户详情
const getUser = async (req, res) => {
  try {
    const { openid } = req.params;
    const user = await userService.getUser(openid);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    res.json({
      success: true,
      data: user
    });
  } catch (error) {
    console.error('获取用户详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户详情失败'
    });
  }
};

// 更新用户备注
const updateUserRemark = async (req, res) => {
  try {
    const { openid } = req.params;
    const { remark } = req.body;
    
    const user = await userService.updateUserRemark(openid, remark);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    res.json({
      success: true,
      data: user
    });
  } catch (error) {
    console.error('更新用户备注失败:', error);
    res.status(500).json({
      success: false,
      message: '更新用户备注失败'
    });
  }
};

// 同步用户信息
const syncUser = async (req, res) => {
  try {
    const { openid } = req.params;
    const user = await userService.syncUser(openid);
    
    res.json({
      success: true,
      data: user
    });
  } catch (error) {
    console.error('同步用户信息失败:', error);
    res.status(500).json({
      success: false,
      message: '同步用户信息失败'
    });
  }
};

module.exports = {
  getUsers,
  getUser,
  updateUserRemark,
  syncUser
};